package com.bluefish.bltuan.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bluefish.bltuan.annotation.RequireRight;
import com.bluefish.bltuan.tools.ActionUtil;
import com.bluefish.bltuan.tools.annotation.StringUtil;
import com.bluefish.bltuan.tools.user.UserRight;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class RightInterceptor implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3308380230428894327L;

	private static final String ADMIN = "/admin";

	private static final String NO_ADMIN_RIGHT = "notAdmin";

	private static final String NO_COMMON_RIGHT = "noRight";
	
	private static Logger log = LoggerFactory.getLogger(RightInterceptor.class);

	public void destroy() {

	}

	public void init() {
		
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		if(needRight(invocation) && !isRightable(invocation)){
			log.info("current action need right but current user is not rightable yet");
			String uri = ActionUtil.getHttpRequest().getServletPath();
			return uri.startsWith(ADMIN) ? NO_ADMIN_RIGHT : NO_COMMON_RIGHT;
		}
		return invocation.invoke();
	}

	private boolean needRight(ActionInvocation invocation) throws SecurityException, NoSuchMethodException {
		String methodName = invocation.getProxy().getMethod();
		Object action = invocation.getAction();
		Method method = action.getClass().getMethod(methodName, (Class[])null);
		if(method.isAnnotationPresent(RequireRight.class)){
			return true;
		}
		if(action.getClass().isAnnotationPresent(RequireRight.class)){
			Annotation an = action.getClass().getAnnotation(RequireRight.class);
			String[] excludes = ((RequireRight)an).exclude();
			return !StringUtil.contains(excludes, methodName);
		}
		return false;
	}

	private boolean isRightable(ActionInvocation invocation) throws SecurityException, NoSuchMethodException{
		UserRight right = ActionUtil.getCurrentUserRight();
		String methodName = invocation.getProxy().getMethod();
		Object action = invocation.getAction();
		Method method = action.getClass().getMethod(methodName, (Class[])null);
		if(method.isAnnotationPresent(RequireRight.class)){
			Annotation an = method.getAnnotation(RequireRight.class);
			UserRight needRight = ((RequireRight)an).right();
			return right.compareTo(needRight) == 0 ? true : false;
		}
		if(action.getClass().isAnnotationPresent(RequireRight.class)){
			Annotation an = action.getClass().getAnnotation(RequireRight.class);
			UserRight needRight = ((RequireRight)an).right();
			return right.compareTo(needRight) == 0 ? true : false;
		}
		return false;
	}

}
